<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" :rules="queryFormRules">
      <!-- <el-form-item label="工单模型" prop="processKey">
        <el-input v-model="queryParams.processKey" placeholder="请输入工单模型" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="模型名称" prop="processName">
        <el-input v-model="queryParams.processName" placeholder="请输入模型名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="工单大类" prop="category" label-width="80px">
        <el-select v-model="queryParams.category" placeholder="请选择" size="small" @change="onCategoryChange">
          <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName" :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单子类" prop="subCategory">
        <el-select v-model="queryParams.subCategory" clearable placeholder="请选择" size="small">
          <el-option
            v-for="item in subCategoryOptions"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryBtn" :loading="queryParams.loading">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQueryBtn">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button  plain icon="el-icon-download" size="mini" v-hasPermi="['workflow:process:startExport']"
          @click="handleExport">导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <el-table v-loading="loading" fit :data="processList" border>
      <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
      <!-- <el-table-column label="工单编号" align="center" prop="businessKey" /> -->
      <!-- <el-table-column label="工单模型" align="center" prop="processKey" :show-overflow-tooltip="true" /> -->
      <!-- <el-table-column label="模型名称" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button type="text" @click="handleProcessView(scope.row)">
            <span>{{ scope.row.processName }}</span>
          </el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="工单大类" align="center" prop="categoryName" :formatter="categoryFormat" />
      <el-table-column label="工单子类" align="center" prop="subCategoryName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button type="text" @click="handleProcessView(scope.row)">
            <span>{{ scope.row.subCategoryName }}</span>
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column label="流程版本" align="center">
        <template slot-scope="scope">
          <el-tag size="medium">v{{ scope.row.version }}</el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="!scope.row.suspended">激活</el-tag>
          <el-tag type="warning" v-if="scope.row.suspended">挂起</el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="部署时间" align="center" prop="deploymentTime" width="180" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-video-play" @click="handleStart(scope.row)"
            v-hasPermi="['workflow:process:start']" :disabled="scope.row.category === 'CB'">发起</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="queryTotal > 0" :total="queryTotal" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 流程图 -->
    <el-dialog :title="processView.title" :visible.sync="processView.open" width="70%" append-to-body>
      <process-viewer :key="`designer-${processView.index}`" :xml="processView.xmlData" :style="{ height: '400px' }" />
    </el-dialog>
  </div>
</template>

<script>
import { listProcess, getBpmnXml, startProcess } from "@/api/workflow/process";
import { reqUpdateWorkStatus } from "@/api/workflow/task";
import { getFormSequence } from "@/api/workflow/comm";
import { listAllCategory, querySubClass } from '@/api/workflow/category'
import ProcessViewer from '@/components/ProcessViewer'
import { mapState } from "vuex";

export default {
  name: 'WorkProcess',
  components: {
    ProcessViewer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processKey: undefined,
        processName: undefined,
        category: undefined,
        loading: false,
        subCategory: ''
      },
      queryFormRules: {
        'category': [
          { required: true, message: '请选择工单大类', trigger: 'change' }
        ]
      },
      // 显示搜索条件
      showSearch: true,
      // 总条数
      queryTotal: 0,
      filterCategoryText: '',
      categoryOptions: [],
      categoryProps: {
        label: 'categoryName',
        value: 'code'
      },
      subCategoryOptions: [],
      // 流程定义表格数据
      processList: [],
      processView: {
        title: '',
        open: false,
        index: undefined,
        xmlData: "",
      }
    }
  },
  computed: {
    ...mapState(["user"]),
  },
  created() {
    this.getCategoryList();
    this.getList();
  },
  methods: {
    /** 查询流程分类列表 */
    getCategoryList() {
      listAllCategory().then(response => this.categoryOptions = response.data)
    },
    /** 查询流程定义列表 */
    getList() {
      this.queryParams.loading = true
      this.loading = true;
      if (this.queryParams) {
        if (this.queryParams.subCategory && Array.isArray(this.queryParams.subCategory)) {
          this.queryParams.subCategoryId = this.queryParams.subCategory[this.queryParams.subCategory.length - 1]
        } else {
          this.queryParams.subCategoryId = this.queryParams.subCategory
        }
      }
      listProcess(this.queryParams).then(response => {
        this.processList = response.rows;
        this.queryTotal = response.total;
        this.loading = false
        this.queryParams.loading = false
      })
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQueryBtn() {
      this.$refs['queryForm'].validate((valid) => {
        if (valid) {
          this.handleQuery()
        }
      });
    },
    /** 重置按钮操作 */
    resetQueryBtn() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看流程图 */
    handleProcessView(row) {
      let definitionId = row.definitionId;
      this.processView.title = "流程图";
      this.processView.index = definitionId;
      // 发送请求，获取xml
      getBpmnXml(definitionId).then(res => {
        this.processView.xmlData = res.data;
      })
      this.processView.open = true;
    },
    onCategoryChange(val) {
      let categoryItem = this.categoryOptions.find(item => { return item.code === val })
      if (categoryItem) {
        this.queryParams.subCategory = ''
        querySubClass({
          'firstCategoryId': categoryItem.categoryId
        }).then((response)=>{
          this.subCategoryOptions = response.rows
        })
      }
    },
    handleStart(row) {
      // 催办类工单只能催办专员发起
      if (row.category === 'CB' && !this.isCbCommissione()) {
        this.$alert('当前用户无权限操作', "系统提示", { dangerouslyUseHTMLString: true });
        return
      } /*else if (row.category === 'YJ' && !this.isDeptSbRg()) {
        // 集约报岗类工单，“发起”操作目前仅支持 2个业务中心（收包业务中心 和 人广业务中心）
        this.$alert('当前用户无权限操作', "系统提示", { dangerouslyUseHTMLString: true });
        return
      } */else if (row.subRoleId && row.subRoleId.length) {
        let isOK = false
        let user = this.$store.state.user.userInfo;
        for (const role of row.subRoleId.split(',')) {
          isOK = user.roles.find(item => { return item.roleId === role })
          if (isOK) { break }
        }
        if (!isOK) {
          this.$alert('当前用户无权限操作', "系统提示", { dangerouslyUseHTMLString: true });
          return
        }
      }

      // this.$router.push({
      //   path: '/workflow/process/start/' + row.deploymentId,
      //   query: {
      //     definitionId: row.definitionId,
      //   }
      // })
      if (row.definitionId) {
        getFormSequence({'name': row.subCategory, length: '10'}).then(res => {
          return new Promise((resolve, reject) => {
            resolve(res.data)
          })
        }).then(data => {
          startProcess(row.definitionId, {'businessKey': data.seq}).then(res => {
            reqUpdateWorkStatus(
              {
                businessKey: data.seq,
                businessStatus: "6", // 初始
                taskId: res.data.taskId,
              }
            ).then(r => {
              this.$router.push({
                path: '/workflow/process/start/' + row.deploymentId,
                query: {
                  definitionId: row.definitionId,
                  procInsId: res.data.procInsId,
                  taskId: res.data.taskId,
                  'cur_category': row.categoryName,
                  'cur_subcategory': row.subCategoryName,
                  'cur_businessKey': data.seq
                }
              })
            })
          })
        })
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('workflow/process/startExport', {
        ...this.queryParams
      }, `wf_start_process_${new Date().getTime()}.xlsx`)
    },
    categoryFormat(row, column) {
      return this.categoryOptions.find(k => k.code === row.category)?.categoryName ?? '';
    },
    /**
     * 当前用户是否是催办专员
     */
    isCbCommissione() {
      let user = this.$store.state.user.userInfo;
      let cbJyRole = user.roles.find(item => { return item.roleKey === 'role_ywhy_jycbsbcb_commissioner' })
      return cbJyRole
    },
    /**
     * 集约报岗类工单，“发起”操作目前仅支持 2个业务中心（收包业务中心 和 人广业务中心）
     */
     isDeptSbRg() {
      let user = this.$store.state.user.userInfo;
      return ['收包业务', '人民广场'].some(item => { return -1 !== user.deptName.search(item) })
    }
  }
}
</script>

<style scoped></style>
